import { NzMessageService } from 'ng-zorro-antd/message';
/*
 * @Author: lusy lucy_202306@163.com
 * @Date: 2022-11-22 11:20:57
 * @LastEditors: lusy lucy_202306@163.com
 * @LastEditTime: 2022-11-28 09:28:05
 * @FilePath: \text\src\app\views\personal-center\personal-center.component.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Component, Injectable, OnInit } from '@angular/core';
import { UserService } from 'src/app/service/user.service';
import { WebsocketService } from 'src/app/service/websocket.service';

@Component({
  selector: 'app-personal-center',
  templateUrl: './personal-center.component.html',
  styleUrls: ['./personal-center.component.less']
})

@Injectable()
export class PersonalCenterComponent implements OnInit{
  constructor(
    private user: UserService,
    private websocketService: WebsocketService,
    private message: NzMessageService
  ){}

  ws!: WebSocket;
  server_url: string = '172.16.32.175:8632';
  token: string = JSON.parse(localStorage.getItem('Token')!)
  messageCnt: number | undefined


  ngOnInit(): void {
    this.createWebSocket(false)
  }

  // 启动websocket
  createWebSocket(is_reconnect: boolean) {
    try {
      this.ws = new WebSocket(`ws:${this.server_url}/ws`)
      this.init(is_reconnect)
    } catch (error) {
      this.reconnect()
    }
  }

  init(is_reconnect: boolean) {
    // 连接成功的回调
    this.ws.onopen = (e)=>{
      console.log('websocket:已连接')
      // 连接建立后第一次向服务端发送信息
      this.ws.send(JSON.stringify({
        token: this.token
      }))
      // 心跳检测重置
      this.heartCheckReset()
    }

    // 接收消息的回调
    this.ws.onmessage = (e)=>{
      this.messageCnt = JSON.parse(e.data).unreadCount
      if(this.messageCnt! > 0) this.message.success('新消息来啦')
    }

    // 连接发生错误的回调
    this.ws.onerror = (e)=>{
      console.log("WebSocket:发生错误" + e);
      this.reconnect()
    }

    // 连接关闭的回调
    this.ws.onclose = (e)=>{
      console.log('websocket 已关闭')
      this.heartCheckReset()
      this.reconnect()
    }

    // 监听窗口关闭事件
    window.onbeforeunload = ()=>{
      this.ws.close()
    }
  }


  // 避免重复连接
  lockReconnect: boolean = false
  tt: any

  // websocket重连
  reconnect() {
    if(this.lockReconnect) return
    this.lockReconnect = true
    this.tt && clearTimeout(this.tt)
    this.tt = setTimeout(()=>{
      console.log('重连中。。。')
      this.lockReconnect = false
      this.createWebSocket(true)
    }, 4000)
  }

  timeoutObj = null
  serverTimeoutObj = null

  heartCheckReset() {
    clearTimeout(this.timeoutObj!)
    clearTimeout(this.serverTimeoutObj!)
  }





}
